#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>

#include "message.h"
#include "command.h"

/**
 * \def TABLESIZE(table)
 * \brief A macro returns the number of elements in a \a table.
 */
#define TABLESIZE(table)    (sizeof(table)/sizeof(table[0]))

int qid_snd = 0;
int qid_rcv = 0;

int InitMessage(void)
{
    key_t key;
    
    if((key = ftok("/usr/local/etc/MiniGUI.cfg",'a')) == -1)
    {
        perror("ftok.\n");
        return -1;
    }

    if((qid_snd = msgget(key,IPC_CREAT|0666)) == -1)
    {
        printf("msgget.\n");
        return -1;
    }

    if((key = ftok("/usr/local/etc/MiniGUI.cfg",'b')) == -1)
    {
        perror("ftok.\n");
        return -1;
    }

    if((qid_rcv = msgget(key,IPC_CREAT|0666)) == -1)
    {
        perror("msgget.\n");
        return -1;
    }    
    printf("Open queue,qid_snd %d,qid_rcv %d\n",qid_snd,qid_rcv);

    return 0;
}

int SendMessage(const char *pMessage)
{
    struct message msg_snd = {0};

    if(NULL == pMessage){
        return -1;
    }

    strcpy(msg_snd.msg_text,pMessage);
    msg_snd.msg_type = getpid();

    if((msgsnd(qid_snd,&msg_snd,strlen(msg_snd.msg_text),0)) < 0)
    {
        printf("message posted failed\n");
        return -1;
    }

    return 0;
}

int parse_message(const char *pMessage)
{
    struct message msg_snd;

    memset(&msg_snd,0,sizeof(msg_snd));
    msg_snd.msg_type = getpid();
    char *pstr = cmd_buf;
    memset(pstr,0,CMD_BUF_SIZE + 1);   
    
    if(NULL != strstr(pMessage,"Autotest start"))
    {
        printf("Autotest start\n");
        /*parse xml file*/
        strcpy(pstr,"script");
        if(OK != exec_cmdline(pstr)){
            printf("parse xml file fail\n");
            return -1;       
        }                
    }
    else if(NULL != strstr(pMessage,"Autotest stop"))
    {
        printf("Autotest stop\n");
    }
    else if(NULL != strstr(pMessage,"Manualtest start"))
    {
        printf("Manualtest start\n");
        /*Manual Test*/
        strcpy(pstr,"manual");
        if(OK != exec_cmdline(pstr)){
            printf("parse xml file fail\n");
            return -1;       
        }         
    }
    else if(NULL != strstr(pMessage,"Manualtest stop"))
    {
        printf("Manualtest stop\n");
    }
    else
    {
        printf("%s is not one cmd.\n",pMessage);
    }

    return 0;
}

void ExitMessage(void)
{
    if((msgctl(qid_snd,IPC_RMID,NULL)) < 0)
    {
        printf("msgctl,qid_snd");
    }
    if((msgctl(qid_rcv,IPC_RMID,NULL)) < 0)
    {
        printf("msgctl,qid_rcv");
    }  
}
